package com.douqu.game.core.entity.ext.data.boon;

import com.bean.core.buffer.ByteBuffer;
import com.douqu.game.core.config.ShareConfig;
import com.douqu.game.core.e.E_ShareType;
import com.douqu.game.core.entity.Player;
import com.douqu.game.core.entity.ext.data.BaseData;
import com.douqu.game.core.factory.ConstantFactory;
import com.douqu.game.core.factory.DataFactory;
import com.douqu.game.core.factory.WorldInfoFactory;
import com.douqu.game.core.protobuf.SGCommonProto;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: miracle.
 * Description:
 * Date: 2018/5/24 0024 下午 3:45
 * Huan Yu Copyright (c) 2017 All Rights Reserved.
 */
public class ShareData extends BaseData{

    /**
     * 正在进行的分享
     */
    private Map<Integer,ShareBean> shareBeanMap;

    /**
     * 已经完成的分享
     */
    private Map<Integer,ShareBean> endShareBeanMap;

    private Player player;

    public ShareData(Player player){
        this.player = player;
        endShareBeanMap = new ConcurrentHashMap<>();
        initShareBeanMap();
    }


    /**************** 分享 ********************/
    /**
     * ShareBean 转 SGCommonProto.ShareObject
     * @return
     */
    public List<SGCommonProto.ShareObject> getShareObjectList(){
        refreshShareMap();
        return getShareObjectList(shareBeanMap);
    }

    public SGCommonProto.ShareObject.Builder getShareObject(ShareBean shareBean){
        return SGCommonProto.ShareObject.newBuilder().
                setId(shareBean.getShareId()).
                setState(SGCommonProto.E_SHARE_STATE.forNumber(shareBean.getStateCode()));
    }

    public List<SGCommonProto.ShareObject> getShareObjectList(Map<Integer,ShareBean> map){
        List<SGCommonProto.ShareObject> shareObjectList = new ArrayList<>();
        for (Map.Entry<Integer,ShareBean> entry:map.entrySet()){
            shareObjectList.add(getShareObject(entry.getValue()).build());
        }
        shareObjectList.sort(new Comparator<SGCommonProto.ShareObject>() {
            @Override
            public int compare(SGCommonProto.ShareObject o1, SGCommonProto.ShareObject o2) {
                return new Integer(o1.getId()).compareTo(o2.getId());
            }
        });
        return shareObjectList;
    }

    private void initShareBeanMap(){
        shareBeanMap = new ConcurrentHashMap<>();
        shareBeanMap.put(ConstantFactory.SHARE_MAJOR_LEVEL_UP_ID,
                new ShareBean(ConstantFactory.SHARE_MAJOR_LEVEL_UP_ID,
                        SGCommonProto.E_SHARE_STATE.SHARE_STATE_CANNOTSHARE_VALUE));
        shareBeanMap.put(ConstantFactory.SHARE_ORANGE_NUMBER_ID,
                new ShareBean(ConstantFactory.SHARE_ORANGE_NUMBER_ID,
                        SGCommonProto.E_SHARE_STATE.SHARE_STATE_CANNOTSHARE_VALUE));
        shareBeanMap.put(ConstantFactory.SHARE_RED_NUMBER_ID,
                new ShareBean(ConstantFactory.SHARE_RED_NUMBER_ID,
                        SGCommonProto.E_SHARE_STATE.SHARE_STATE_CANNOTSHARE_VALUE));
        shareBeanMap.put(ConstantFactory.SHARE_PURPLE_UP_STAR_ID,
                new ShareBean(ConstantFactory.SHARE_PURPLE_UP_STAR_ID,
                        SGCommonProto.E_SHARE_STATE.SHARE_STATE_CANNOTSHARE_VALUE));
        shareBeanMap.put(ConstantFactory.SHARE_ORANGE_UP_STAR_ID,
                new ShareBean(ConstantFactory.SHARE_ORANGE_UP_STAR_ID,
                        SGCommonProto.E_SHARE_STATE.SHARE_STATE_CANNOTSHARE_VALUE));
        shareBeanMap.put(ConstantFactory.SHARE_RED_UP_STAR_ID,
                new ShareBean(ConstantFactory.SHARE_RED_UP_STAR_ID,
                        SGCommonProto.E_SHARE_STATE.SHARE_STATE_CANNOTSHARE_VALUE));
        shareBeanMap.put(ConstantFactory.SHARE_PASS_CUSTOMS_ID,
                new ShareBean(ConstantFactory.SHARE_PASS_CUSTOMS_ID,
                        SGCommonProto.E_SHARE_STATE.SHARE_STATE_CANNOTSHARE_VALUE));
        shareBeanMap.put(ConstantFactory.SHARE_SENIORITY_RANK_ID,
                new ShareBean(ConstantFactory.SHARE_SENIORITY_RANK_ID,
                        SGCommonProto.E_SHARE_STATE.SHARE_STATE_CANNOTSHARE_VALUE));

        //init之后查看这些任务是否完成 并修改状态
        refreshShareMap();
    }

    /**
     * 刷新所有分享的完成状态
     * 这里只刷新在进行中且不能分享的 只会刷新到进行中能分享
     * @return
     */
    public void refreshShareMap(){
        ShareConfig shareConfig;
        for (Map.Entry<Integer,ShareBean> entry:shareBeanMap.entrySet()){
            if (entry.getValue().getStateCode() ==
                    SGCommonProto.E_SHARE_STATE.SHARE_STATE_CANNOTSHARE_VALUE){
                shareConfig = DataFactory.getInstance().getGameObject(DataFactory.SHARE_KEY,entry.getKey());
                if (shareConfig != null){
                    if (isCanShare(entry.getKey(),shareConfig)){
                        //如果可以分享
                        entry.getValue().setStateCode(SGCommonProto.E_SHARE_STATE.SHARE_STATE_CANSHARE_VALUE);
                    }
                }
            }
        }
    }

    public boolean majorLevelUp(ShareConfig config){
        //获取主将等级 如果大于配置 则true 否则false
        return player.getLv() >= config.level;
    }

    public boolean cardQualityNumber(ShareConfig config,int quality){
        //判断用户某品质卡数量
        int count = player.getCardData().getCountByQuality(quality);
        return count >= config.level;
    }

    public boolean cardUpStar(ShareConfig config,int quality){
        int highest = player.getCardData().getStarByQuality(quality);
        return highest >= config.level;
    }

    public boolean passCustoms(ShareConfig config){
        return player.getInstanceData().isPassInstance(config.level);
    }

    public boolean seniorityRank(ShareConfig config){
        int rank = WorldInfoFactory.getInstance().getWorldArenaData().getArenaRankByObjectIndex(player);
        return rank == 0? false:rank <= config.level;
    }

    /**
     * 判断一个任务是否可以分享
     * @return
     */
    public boolean isCanShare(int shareId,ShareConfig config){
        if (config.type == E_ShareType.MAJORLEVELUP.getCode()){
            if (majorLevelUp(config))
                return true;
        }else if (config.type == E_ShareType.ORANGENUMBER.getCode()){
            if (cardQualityNumber(config,ConstantFactory.QUALITY_ORANGE))
                return true;
        }else if (config.type == E_ShareType.REDNUMBER.getCode()){
            if (cardQualityNumber(config,ConstantFactory.QUALITY_RED))
                return true;
        }else if (config.type == E_ShareType.PURPLEUPSTAR.getCode()){
            if (cardUpStar(config,ConstantFactory.QUALITY_PURPLE))
                return true;
        }else if (config.type == E_ShareType.ORANGEUPSTAR.getCode()){
            if (cardUpStar(config,ConstantFactory.QUALITY_ORANGE))
                return true;
        }else if (config.type == E_ShareType.REDUPSTAR.getCode()){
            if (cardUpStar(config,ConstantFactory.QUALITY_RED))
                return true;
        }else if (config.type == E_ShareType.PASSCUSTOMS.getCode()){
            if (passCustoms(config))
                return true;
        }else if (config.type == E_ShareType.SENIORITYRANK.getCode()){
            if (seniorityRank(config))
                return true;
        }
        return false;
    }

    public boolean isCanShare(int shareId){
        ShareConfig config = DataFactory.getInstance().getGameObject(DataFactory.SHARE_KEY,shareId);
        if (config == null){
            return false;
        }
        ShareBean bean = shareBeanMap.get(shareId);
        //判断这个任务是否在进行中
        if (bean == null
                || bean.getStateCode() != SGCommonProto.E_SHARE_STATE.SHARE_STATE_CANNOTSHARE_VALUE){
            return false;
        }
        return isCanShare(shareId,config);
    }

    /**
     * 处理当前分享
     * @param shareId
     */
    public boolean handCurrentShare(int shareId,ShareConfig shareConfig){
        if (shareConfig == null){
            DataFactory.getInstance().getGameObject(DataFactory.SHARE_KEY,shareId);
        }

        /**
         * 1.add good to player
         * 2.remove from currentShareMap
         * 3.into endShareMap
         * 4.intoNextShare()
         */
        player.getBagInfo().addGoods(shareConfig.reward);
        shareBeanMap.remove(shareId);
        endShareBeanMap.put(shareId,new ShareBean(shareId,SGCommonProto.E_SHARE_STATE.SHARE_STATE_RECEIVEDREWARD_VALUE));
        return intoNextShare(shareId,shareConfig);
    }

    /**
     * 加入到下一个分享
     * @param shareId
     * @param shareConfig
     * @return
     */
    public boolean intoNextShare(int shareId,ShareConfig shareConfig){
        int nextShardId = shareConfig.afterShare;
        if (nextShardId == 0){
            return false;
        }
        ShareConfig nextConfig = DataFactory.getInstance().getGameObject(DataFactory.SHARE_KEY,nextShardId);
        if (nextConfig == null){
            return false;
        }

        //加入到当前任务
        shareBeanMap.put(nextShardId,new ShareBean(nextShardId,SGCommonProto.E_SHARE_STATE.SHARE_STATE_CANNOTSHARE_VALUE));
        //分享状态验证
        refreshShareMap();
        return true;
    }

    /**
     * 红点任务检测
     * @return
     */
    public boolean checkRedPoint(){
        boolean flag = false;
        ShareConfig shareConfig;
        for (Map.Entry<Integer,ShareBean> entry:shareBeanMap.entrySet()){
            if (entry.getValue().getStateCode() ==
                    SGCommonProto.E_SHARE_STATE.SHARE_STATE_CANNOTSHARE_VALUE){
                shareConfig = DataFactory.getInstance().getGameObject(DataFactory.SHARE_KEY,entry.getKey());
                if (shareConfig != null){
                    if (isCanShare(entry.getKey(),shareConfig)){
                        //如果可以分享
                        entry.getValue().setStateCode(SGCommonProto.E_SHARE_STATE.SHARE_STATE_CANSHARE_VALUE);
                        flag = true;
                        break;
                    }
                }
            }else if(entry.getValue().getStateCode() ==
                    SGCommonProto.E_SHARE_STATE.SHARE_STATE_CANSHARE_VALUE
                    || entry.getValue().getStateCode() ==
                    SGCommonProto.E_SHARE_STATE.SHARE_STATE_CANRECEIVEREWARD_VALUE){
                flag = true;
                break;
            }
        }
        return flag;
    }

    @Override
    public void init() {
        endShareBeanMap = new ConcurrentHashMap<>();
        initShareBeanMap();
    }

    @Override
    public void checkInit() {
        if (shareBeanMap.isEmpty())
            init();
    }

    @Override
    public void reset() {

    }

    @Override
    public void checkReset() {

    }

    @Override
    public void writeTo(ByteBuffer buffer) {
        //shareBeanMap size byte
        //endShareBeanMap size short
        buffer.writeByte(shareBeanMap.size());
        for (Map.Entry<Integer,ShareBean> entry:shareBeanMap.entrySet()){
            buffer.writeShort(entry.getKey());
            entry.getValue().writeTo(buffer);
        }

        buffer.writeShort(endShareBeanMap.size());
        for (Map.Entry<Integer,ShareBean> entry:endShareBeanMap.entrySet()){
            buffer.writeShort(entry.getKey());
            entry.getValue().writeTo(buffer);
        }
    }

    @Override
    public void loadFrom(ByteBuffer buffer) {
        int size = buffer.readByte();
        shareBeanMap = new ConcurrentHashMap<>();
        for (int i = 0; i < size; i ++){
            int key = buffer.readShort();
            shareBeanMap.put(key,new ShareBean(key,buffer));
        }

        size = buffer.readShort();
        endShareBeanMap = new ConcurrentHashMap<>();
        for (int i = 0; i < size; i ++){
            int key = buffer.readShort();
            endShareBeanMap.put(key,new ShareBean(key,buffer));
        }
    }

    public Map<Integer, ShareBean> getShareBeanMap() {
        return shareBeanMap;
    }

    public void setShareBeanMap(Map<Integer, ShareBean> shareBeanMap) {
        this.shareBeanMap = shareBeanMap;
    }

    public Map<Integer, ShareBean> getEndShareBeanMap() {
        return endShareBeanMap;
    }

    public void setEndShareBeanMap(Map<Integer, ShareBean> endShareBeanMap) {
        this.endShareBeanMap = endShareBeanMap;
    }
}
